from flask import Blueprint, request, jsonify
from flask_login import login_required, current_user
from app import db
from app.models.objective import Objective, KeyResult
from app.models.status import ProgressUpdate
from app.utils.decorators import manager_required
from datetime import datetime

bp = Blueprint('objectives', __name__, url_prefix='/api/objectives')

@bp.route('', methods=['GET'])
@login_required
def get_objectives():
    """获取目标列表"""
    # 获取查询参数
    owner_id = request.args.get('owner_id', type=int)
    level = request.args.get('level')
    status = request.args.get('status')
    include_children = request.args.get('include_children', 'false').lower() == 'true'

    query = Objective.query

    # 权限过滤：员工只能看自己的目标
    if not current_user.is_manager():
        query = query.filter_by(owner_id=current_user.id)
    elif owner_id:
        query = query.filter_by(owner_id=owner_id)

    if level:
        query = query.filter_by(level=level)
    if status:
        query = query.filter_by(status=status)

    objectives = query.order_by(Objective.created_at.desc()).all()
    return jsonify([obj.to_dict(include_children=include_children) for obj in objectives]), 200

@bp.route('/<int:id>', methods=['GET'])
@login_required
def get_objective(id):
    """获取单个目标详情"""
    objective = Objective.query.get_or_404(id)

    # 权限检查
    if not current_user.is_manager() and objective.owner_id != current_user.id:
        return jsonify({'error': 'Access denied'}), 403

    return jsonify(objective.to_dict(include_children=True)), 200

@bp.route('', methods=['POST'])
@login_required
def create_objective():
    """创建目标"""
    data = request.get_json()

    required_fields = ['title', 'level', 'type', 'start_date', 'end_date']
    if not all(field in data for field in required_fields):
        return jsonify({'error': 'Missing required fields'}), 400

    # 权限检查：只有管理者能创建公司级和部门级目标
    if data['level'] in ['company', 'department'] and not current_user.is_manager():
        return jsonify({'error': 'Insufficient permissions'}), 403

    objective = Objective(
        title=data['title'],
        description=data.get('description'),
        owner_id=data.get('owner_id', current_user.id),
        level=data['level'],
        type=data['type'],
        parent_id=data.get('parent_id'),
        start_date=datetime.strptime(data['start_date'], '%Y-%m-%d').date(),
        end_date=datetime.strptime(data['end_date'], '%Y-%m-%d').date()
    )

    db.session.add(objective)
    db.session.commit()

    # 如果提供了关键成果，一并创建
    if 'key_results' in data:
        for kr_data in data['key_results']:
            kr = KeyResult(
                objective_id=objective.id,
                title=kr_data['title'],
                description=kr_data.get('description'),
                target_value=kr_data['target_value'],
                unit=kr_data.get('unit')
            )
            db.session.add(kr)

    db.session.commit()

    # 如果创建的是个人目标且有父目标，自动更新父目标的进度
    if objective.parent_id:
        parent_objective = Objective.query.get(objective.parent_id)
        if parent_objective:
            parent_objective.calculate_progress()
            db.session.commit()

    return jsonify(objective.to_dict()), 201

@bp.route('/<int:id>', methods=['PUT'])
@login_required
def update_objective(id):
    """更新目标"""
    objective = Objective.query.get_or_404(id)

    # 权限检查
    if not current_user.is_manager() and objective.owner_id != current_user.id:
        return jsonify({'error': 'Access denied'}), 403

    data = request.get_json()

    # 记录进度变化
    if 'progress' in data and data['progress'] != objective.progress:
        progress_update = ProgressUpdate(
            objective_id=objective.id,
            previous_value=objective.progress,
            new_value=data['progress'],
            notes=data.get('notes'),
            updated_by=current_user.id
        )
        db.session.add(progress_update)

    # 更新字段
    updatable_fields = ['title', 'description', 'progress', 'status']
    for field in updatable_fields:
        if field in data:
            setattr(objective, field, data[field])

    if 'start_date' in data:
        objective.start_date = datetime.strptime(data['start_date'], '%Y-%m-%d').date()
    if 'end_date' in data:
        objective.end_date = datetime.strptime(data['end_date'], '%Y-%m-%d').date()

    db.session.commit()

    # 如果更新的是个人目标且有进度变化，自动更新父目标（部门目标）的进度
    if 'progress' in data and objective.parent_id:
        parent_objective = Objective.query.get(objective.parent_id)
        if parent_objective:
            parent_objective.calculate_progress()
            db.session.commit()

    return jsonify(objective.to_dict()), 200

@bp.route('/<int:id>', methods=['DELETE'])
@login_required
def delete_objective(id):
    """删除目标"""
    objective = Objective.query.get_or_404(id)

    # 权限检查
    if not current_user.is_manager() and objective.owner_id != current_user.id:
        return jsonify({'error': 'Access denied'}), 403

    db.session.delete(objective)
    db.session.commit()
    return jsonify({'message': 'Objective deleted successfully'}), 200

@bp.route('/sync', methods=['POST'])
@manager_required
def sync_objectives():
    """同步目标到下属"""
    data = request.get_json()
    objective_id = data.get('objective_id')
    subordinate_ids = data.get('subordinate_ids', [])

    if not objective_id or not subordinate_ids:
        return jsonify({'error': 'objective_id and subordinate_ids required'}), 400

    objective = Objective.query.get_or_404(objective_id)

    # 检查是否有权限同步该目标
    if objective.owner_id != current_user.id:
        return jsonify({'error': 'You can only sync your own objectives'}), 403

    synced = objective.sync_to_subordinates(subordinate_ids)
    db.session.commit()

    return jsonify({
        'message': f'Objective synced to {len(synced)} subordinates',
        'synced_objectives': [obj.to_dict() for obj in synced]
    }), 201

@bp.route('/<int:id>/key_results', methods=['POST'])
@login_required
def add_key_result(id):
    """为目标添加关键成果"""
    objective = Objective.query.get_or_404(id)

    # 权限检查
    if not current_user.is_manager() and objective.owner_id != current_user.id:
        return jsonify({'error': 'Access denied'}), 403

    data = request.get_json()
    required_fields = ['title', 'target_value']
    if not all(field in data for field in required_fields):
        return jsonify({'error': 'Missing required fields'}), 400

    kr = KeyResult(
        objective_id=objective.id,
        title=data['title'],
        description=data.get('description'),
        target_value=data['target_value'],
        unit=data.get('unit')
    )

    db.session.add(kr)
    db.session.commit()

    return jsonify(kr.to_dict()), 201

@bp.route('/key_results/<int:id>', methods=['PUT'])
@login_required
def update_key_result(id):
    """更新关键成果"""
    kr = KeyResult.query.get_or_404(id)

    # 权限检查
    if not current_user.is_manager() and kr.objective.owner_id != current_user.id:
        return jsonify({'error': 'Access denied'}), 403

    data = request.get_json()

    # 记录进度变化
    if 'current_value' in data and data['current_value'] != kr.current_value:
        progress_update = ProgressUpdate(
            key_result_id=kr.id,
            previous_value=kr.current_value,
            new_value=data['current_value'],
            notes=data.get('notes'),
            updated_by=current_user.id
        )
        db.session.add(progress_update)
        kr.current_value = data['current_value']
        kr.update_progress()

    updatable_fields = ['title', 'description', 'target_value', 'unit', 'status']
    for field in updatable_fields:
        if field in data:
            setattr(kr, field, data[field])

    # 更新目标的总体进度
    kr.objective.calculate_progress()

    db.session.commit()
    return jsonify(kr.to_dict()), 200

@bp.route('/key_results/<int:id>', methods=['DELETE'])
@login_required
def delete_key_result(id):
    """删除关键成果"""
    kr = KeyResult.query.get_or_404(id)

    # 权限检查
    if not current_user.is_manager() and kr.objective.owner_id != current_user.id:
        return jsonify({'error': 'Access denied'}), 403

    objective = kr.objective
    db.session.delete(kr)
    objective.calculate_progress()
    db.session.commit()

    return jsonify({'message': 'Key result deleted successfully'}), 200